package com.acme.iolab.filesend.nio;


import com.acme.iolab.filesend.FileServer;
import com.acme.iolab.filesend.IntToByteArrayConverter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NIOFileServer extends FileServer {

    private ServerSocketChannel sock;

    public NIOFileServer(int port) throws IOException {
        super(port);
        sock = ServerSocketChannel.open();
        sock.bind(new InetSocketAddress(port));
    }

    @Override
    public void process(String savePath) throws IOException {
        try (SocketChannel socketChannel = sock.accept();
             FileChannel fileChannel = new FileOutputStream(savePath).getChannel()) {

            System.out.println("accepted connection.");
            long start = System.currentTimeMillis();

            final ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
            socketChannel.read(sizeBuffer);
            int size = IntToByteArrayConverter.convertBack(sizeBuffer);
            System.out.println("start reading... size:" + size);

            fileChannel.transferFrom(socketChannel, 0, size);

            System.out.println("filed saved in: " + (System.currentTimeMillis() - start));
            socketChannel.write(ByteBuffer.allocate(1));
            System.out.println("finished.");

            socketChannel.close();
        }
    }
}
